using System;
using System.Collections.Generic;
using MSOffice = Microsoft.Office.Core;
using MSOutlook = Microsoft.Office.Interop.Outlook;

namespace Microsoft.Sample.Outlook.Utility
{

	/// <summary>
	/// Utility class to wrap the management of a custom toolbar on an explorer or inspector window. Once the toolbar
	/// is attached to an explorer or inspector, the toolbar class automatically handles the idiosyncrasies of the 
	/// Explorers and Inspectors, including automatically destroying the toolbar when the window closes.
	/// </summary>
    public sealed class Toolbar : CommandBar
	{
		private MSOffice.MsoBarPosition _position = MSOffice.MsoBarPosition.msoBarTop;
		List<ToolbarControl> _controls = new List<ToolbarControl>();


		public MSOffice.MsoBarPosition  Position
		{
			get { return _position; }
			set { _position = value; }
		}

		public IList<ToolbarControl> Controls
		{
			get { return _controls; }
		}

        public Toolbar(string name)
            : base(name)
        {
        }

        public Toolbar(string name, CommandBarWindowType windowType)
            : base(name, windowType)
        {
        }

		/// <summary>
		/// Attach this toolbar to the specified window
		/// </summary>
		/// <param name="window"></param>
		internal override void Attach(WindowAdapter window)
		{
			//Get the command bars collection from the window. 
			MSOffice.CommandBars bars = window.CommandBars;
			if (bars == null)
				throw new ApplicationException("CommandBars property was null");

			//Look for the existance of a commandbar with a matching name already on the window
			MSOffice.CommandBar bar = null;
			foreach (MSOffice.CommandBar b in bars)
			{
				if (b.Name == this.Name)
				{
					bar = b;
					bar.Position = this.Position;
					break;
				}
			}

			//If there is no commandbar  with a matching name, create it
			if (bar == null)
			{
				bar = bars.Add(this.Name, this.Position, false, true);
			}
            
			//Attach the toolbar controls to the window command bar
			foreach (ToolbarControl ctrl in this.Controls)
				ctrl.Attach(bar, window);

            //Show and enable the toolbar
            ShowCommandBar(window, bar);

            window.SelectionChange += delegate(object sender, EventArgs args)
            {
                ShowCommandBar(window, bar);
            };

			Windows.Add(window);
		}

		/// <summary>
		/// Detach the toolbar from a window that's closing
		/// </summary>
		/// <param name="window"></param>
		internal override void Detach(WindowAdapter window)
		{
            Windows.Remove(window);

			if (window.CommandBars != null)
			{
				foreach (MSOffice.CommandBar bar in window.CommandBars)
				{
					if (bar.Name == this.Name)
						bar.Delete();
				}
			}
		}
	}

}
